<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/zepto/1.1.6/zepto.min.js"></script>
<script id="PostListTemplate" type="text/html">
	<ul>
		<li>
			<span class="id"></span>, <span class="content"></span>
			<a href="javascript:void(0)" class="edit">edit</a>
			<a href="javascript:void(0)" class="delete">del</a>
		</li>
		<li>
			<form>
				<input name="content"/>
			</form>
		</li>
	</ul>
</script>
<script>
function PostList(element,template) {
	var self = this;
	var url = '/api.php/records/posts';
	self.edit = function() {
		var li = $(this).parent('li');
		var id = li.find('span.id').text();
		var content = li.find('span.content').text();
		content = prompt('Value', content);
		if (content!==null) {
			$.ajax({url: url + '/' + id, type: 'PUT', data: {content: content}, success: self.update});
		}
	};
	self.delete = function() {
		var li = $(this).parent('li');
		var id = li.find('span.id').text();
		if (confirm("Deleting #" + id + ". Continue?")) {
			$.ajax({url: url + '/' + id, type: 'DELETE', success: self.update});
		}
	};
	self.submit = function(e) {
		e.preventDefault();
		var content = $(this).find('input[name="content"]').val();
		$.post(url, {user_id: 1, category_id: 1, content: content}, self.update);
	};
	self.render = function(data) {
		data = data;
		element.html(template.html());
		var item = element.find('li').first().remove();
		for (var i=0;i<data.records.length; i++) {
			var clone = item.clone();
			clone.find('span').each(function(){
				var field = $(this).attr("class");
				$(this).text(data.records[i][field]);
			});
			clone.insertBefore(element.find('li').last());
		}
	};
	self.update = function() {
		$.get(url, self.render);
	};
	self.post = function() {
		$.post(url, {user_id: 1, category_id: 1, content: "from zepto"}, self.update);
	};
	element.on('submit', 'form', self.submit);
	element.on('click', 'a.edit', self.edit);
	element.on('click', 'a.delete', self.delete);
	self.post();
};
$(function(){
	new PostList($('#PostListDiv'), $('#PostListTemplate'));
});
</script>
</head>
<body>
<div id="PostListDiv">Loading...</div>
</body>
</html>

